<template>
  <!-- 外部渠道订单列表 -->
  <customContainer ref="mainRef" :config="config" />
  <div>
    <!-- 批量导入 -->
    <el-dialog
      v-model="open1"
      :title="title"
      width="30%"
      :before-close="cancle1"
    >
      <el-upload
        ref="plUpload"
        class="upload-demo"
        drag
        multiple
        accept=".xlsx,.xls"
        action="#"
        :file-list="fileList"
        :auto-upload="false"
        :on-remove="handleRemove"
        :on-change="handleFileChange"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">提示:仅允许导入"xls"或"xlsx"格式文件!</div>
          <el-link
           
            type="info"
            style="font-size: 12px;color: red;"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="info" @click="cancle1">取消</el-button>
          <el-button v-loading="btnloading" type="primary" @click="submit1">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 批量修改价格 -->
    <el-dialog
      v-model="priceDialog"
      title="批量修改价格"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="priceRef"
        :model="editPriceForm"
        label-width="80px"
        :rules="pieceRules"
      >
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="editPriceForm.unitPrice" style="width: 175px;"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submit2">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <OrderDetail ref="detailRef" @refush="init"></OrderDetail>
    <feeName ref="feeRef"></feeName>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, getCurrentInstance, defineAsyncComponent } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElButton, ElMessageBox, ElMessage, ElDivider } from 'element-plus'
import { DictDirection } from '@/store/modules/dicts'
import { deleteInfo4 } from '@/api/expressManager/fedex'
import { orderList, importOrder, externalCompelPrint } from '@/api/expressManager/external'
import { PlayBarCode, downLoadTag, editOrderStatus9, editPrice, updateOrderStatus, kj } from '@/api/expressManager/orderList'
import userStore from '@/store/modules/user'

const feeName = defineAsyncComponent(() => import('./components/feeName.vue'))
const OrderDetail = defineAsyncComponent(() => import('./components/orderDetail.vue'))
const SelfDropdown = defineAsyncComponent(() => import('./components/SelfDropdown.vue'))
const { proxy } = getCurrentInstance() as any
const user = userStore()
const feeRef = ref(undefined)
const deptIds = user.user.deptId
const open1 = ref(false)
const mainRef = ref(null)
const btnloading = ref(false)
const title = ref(null),
  single = ref(true),
  multiple = ref(true),
  {
    appContext: {
      config: {
        globalProperties: { $download, $validateForm },
      },
    },
  } = getCurrentInstance()
const fileList = ref([])
const priceDialog = ref(false)
const detailRef = ref(null)
// const handleUploadClearance = () => {
//   open1.value = true
//   title.value = '上传清关资料'
// }
const handleFileChange = (file, fileList) => {
  fileList.value = fileList
}
const handleRemove = (file, fileList) => {
  fileList.value = fileList
}
// 导入订单
const handleImport = () => {
  open1.value = true
  title.value = '导入订单'
}
// 下载模板
const importTemplate = () => {
  $download('order/order/info/templateDownLoad/9', {}, `orderTemplate_${ new Date().getTime() }.xlsx`)
}

const submit1 = () => {
  btnloading.value = true
  const data = new FormData()
  proxy.fileList.forEach(el => {
    data.append('file', el.raw)
  })
  const deptId = queryParams.value.deptId
  const ds = queryParams.value.dataSource
  return importOrder(deptId, ds, data).then(res => {
    if (res.code == 200) {
      open1.value = false
      ElMessage.success(res.msg)
      mainRef.value.getList()
      proxy.$refs.plUpload.clearFiles()
      btnloading.value = false
    } else {
      ElMessage.error(res.msg)
      btnloading.value = false
    }
  }).catch(err => {
    console.log(err)
    btnloading.value = false
    proxy.$refs.plUpload.clearFiles()
  })
}
const cancle1 = () => {
  open1.value = false
  proxy.$refs.plUpload.clearFiles()
}
// 批量修改价格
const priceRef = ref(null)
const editPriceForm = ref({ unitPrice: undefined })
const pieceRules = {
  unitPrice: [{ required: true, message: '必填', trigger: 'blur' }],
}
const submit2 = () => {
  const xg = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  const orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
  const unitPrice = editPriceForm.value.unitPrice
  if (xg == 0) {
    ElMessage.error('订单状态为未签入的不能修改单价')
  } else {
    $validateForm(priceRef.value, () => {
      editPrice({ orderNos, unitPrice }).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改单价成功!')
          priceDialog.value = false
          editPriceForm.value.unitPrice = ''
          init()
        } else {
          return ElMessage.error('修改单价失败')
        }
      }).catch(() => {
        editPriceForm.value.unitPrice = ''
      })
    })
  }
}
const handleExport = () => {
  const data = queryParams.value
  $download('order/externalChannels/orderExport', data, `外部渠道列表_${ new Date().getTime() }.xlsx`)
}
const handleClose = () => {
  priceDialog.value = false
}
// 强制制单
const handleForcePlaceOrder = () => {
  let orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
  typeof orderNos == 'string' && (orderNos = [orderNos])
  const xg = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  if (xg == 1) {
    ElMessageBox.confirm('确认强制制单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      externalCompelPrint(orderNos).then(res => {
        if (res.code == 200) {
          ElMessage.success('强制制单成功')
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  } else {
    ElMessageBox.alert('含有不是签入状态的订单，不能强制制单')
  }
}
// 下拉菜单方法调用
const selfDropdownFn = (fnName) => (row) => {
 
}

const handleUpdate = (row: { [key: string]: any }) => {
  detailRef.value.open = true
  detailRef.value.orderNos = row.orderNo
  detailRef.value.idss = row.id
  detailRef.value.title = '修改订单'
  detailRef.value.initData()
}
const handleRouterPush = (row: { [key: string]: any }) => {
  detailRef.value.open = true
  detailRef.value.orderNos = row.orderNo
  detailRef.value.idss = row.id
  detailRef.value.title = '订单详情'
  detailRef.value.initData()
}

const exportDatails = () => {
  const data = queryParams.value
  let orderNos1 = JSON.parse(JSON.stringify(orderNoLists.value))
  typeof orderNos1 == 'string' && (orderNos1 = [orderNos1])
  const orderNo = orderNos1.join(',')
  data.orderNo = orderNo
  $download('order/order/info/exportDatails', data, `运单详情表_${ new Date().getTime() }.xlsx`)
}
// 打标签
const handlePrintLabel = () => {
  const orderNoList = JSON.parse(JSON.stringify(orderNoLists.value)) 

  if (orderNoList.length > 5) {
    ElMessage.error('打标签最多只能选5个')
  } else {
    return PlayBarCode({ orderNoList }).then(res => {
      if (res.code == 200) {
        mainRef.value.getList()
        for (let i = 0; i < res.data.length; i++) {
          window.open(res.data[i], `${ i }jj`)
        }
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
}
const DownLoadTag = () => {
  const zd = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  if (zd[0] != 2) {
    ElMessage.error('只有订单状态为制单,才可以打印面单')
  } else {
    const orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
    // typeof orderNos == 'string' && (orderNos = [orderNos])
    // const orderNos1 = orderNos.join(',')
    downLoadTag({ orderNoList: orderNos }).then(res => {
      if (res.code == 200) {
        for (let i = 0; i < res.data.urlList.length; i++) {
          const urlList = unescape(res.data.urlList[i])
          window.open(urlList, `${ i }a`)
        }
        ElMessage.success(res.mag)
      } else {
        ElMessage.error(res.mag)
      }
    }).catch(err => {
      console.log(err)
    })
  }
}
// 签入
const handleCheckIn = (row: { [key: string]: any }) => {
  console.log(row)
  const xg = JSON.parse(JSON.stringify(selectSplittingStatus.value))
  const orderNos = JSON.parse(JSON.stringify(orderNoLists.value))
  const data = {
    orderNoList: orderNos,
    deptId: queryParams.value.deptId,
  }
  if (xg != 0) {
    ElMessageBox.confirm('确认签入？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      editOrderStatus9(data).then(res => {
        if (res.code == 200) {
          ElMessage.success('签入成功')
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  } else {
    ElMessage.error('只有未签入的订单才能签入')
  }
}
// 退回制单
const handleSeniorUpdate = (row: { [key: string]: any }) => {
  const orderNos = row.orderNo
  ElMessageBox.confirm('此操作将退回到制单状态, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    updateOrderStatus({ orderNo: orderNos }).then(res => {
      if (res.code == 200) {
        ElMessage.success('退回成功')
        mainRef.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
// 扣件
const handleFasteners = (row: { [key: string]: any }) => {
  const orderNos = row.orderNo
  ElMessageBox.confirm('敏感操作！是否继续？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    kj(orderNos).then(res => {
      if (res.code == 200) {
        ElMessage.success('扣件成功')
        mainRef.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const handleUps = () => {}
const retuenDel = (row: { [key: string]: any }) => {
  ElMessageBox.prompt('请输入备注', '提示', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    inputPattern: /\S/,
    inputErrorMessage: '备注不能为空',
  }).then(({ value }) => {
    const ids = [JSON.parse(JSON.stringify(row.id))]
    const remaraks = value
    const data = {
      remarks: remaraks,
      orderNo: row.orderNo,
    }
    deleteInfo4(ids, data).then(res => {
      if (res.code == 200) {
        ElMessage.success('撤单成功')
        mainRef.value.getList()
        init()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const playUps = () => {}
const handlePrintLabel2 = (row: { [key: string]: any }) => {
  const orderNoList = [JSON.parse(JSON.stringify(row.orderNo))]
  PlayBarCode({ orderNoList }).then(res => {
    if (res.code == 200) {
      mainRef.value.getList()
      for (let i = 0; i < res.data.length; i++) {
        window.open(res.data[i], `${ i }jj`)
      }
    }
  })
}
const handleManagementOfSurcharges = (row: { [key: string]: any }) => {
  feeRef.value.feeOpen = true
  feeRef.value.title = '应收费管理'
  feeRef.value.orderNoss = row.orderNo
  feeRef.value.getList(row.orderNo)
}
const queryParams = ref({
  pageSize: 10,
  pageNum: 1,
  dataSource: 1,
  deptId: deptIds,
  clientId: undefined,
  orderNo: undefined,
  waybillNo: undefined,
  mainTransferOrderNo: undefined,
  transportType: 9,
  productType: undefined,
  customerCode: undefined,
  areaCode: undefined,
  receivingSite: undefined,
  marketProducts: undefined,
  goodsType: undefined,
  isPod: undefined,
  businessManager: undefined,
  consigneeCountry: undefined,
  consigneePostcode: undefined,
  splittingStatus: undefined,
  maker: undefined,
  tagNumber: undefined,
  dataSources: undefined,
  pickingStatus: undefined,
})
const init = () => {
  queryParams.value.pageNum = 1
  mainRef.value.getList()
}
const orderNoLists = ref([])
const selectSplittingStatus = ref([])
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  single.value = rows.length != 1
  multiple.value = !rows.length
  selectSplittingStatus.value = rows.map(el => el.splittingStatus)
  orderNoLists.value = rows.map((item) => item.orderNo)
}
const config = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '系统订单号',
            prop: 'orderNo',
            option: {
              placeholder: '请输入系统订单号',
              type: 'textarea',
            },
          },
          {
            label: '客户单号',
            prop: 'waybillNo',
            option: {
              placeholder: '请输入系统订单号',
              type: 'textarea',
            },
          },
          {
            label: '主转单号',
            prop: 'mainTransferOrderNo',
            option: {
              placeholder: '请输入系统订单号',
              type: 'textarea',
            },
          },
          {
            type: 'select',
            label: '客户名称',
            prop: 'customerCode',
            option: {
              dictInfo: { dict: DictDirection.客户 },
            },
          },
          {
            type: 'select',
            label: '所属站点',
            prop: 'areaCode',
            option: {
              dictInfo: { dict: DictDirection.收货站点 },
            },
          },
          {
            type: 'select',
            label: '拣货站点',
            prop: 'receivingSite',
            option: {
              dictInfo: { dict: DictDirection.收货站点 },
            },
          },
		
          {
            type: 'select',
            label: '销售产品',
            prop: 'marketProducts',
            option: {
              dictInfo: { dict: DictDirection.产品 },
            },
          },
          {
            type: 'select',
            label: '收货类型',
            prop: 'goodsType',
            option: {
              dictInfo: { dict: DictDirection.货物类型 },
            },
          },
          {
            type: 'select',
            label: '业务员',
            prop: 'businessManager',
            option: {
              dictInfo: { dict: DictDirection.业务员 },
            },
          },
          {
            type: 'selectv2',
            label: '目的国家',
            prop: 'consigneeCountry',
            option: {
              dictInfo: { dict: DictDirection.国家 },
            },
          },
          {
            label: '邮编',
            prop: 'consigneePostcode',
            option: {
              controls: false,
            },
          },

          {
            type: 'date-picker',
            label: '创建日期',
            prop: 'datePicker',
            option: {
              type: 'date',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            type: 'select',
            label: '订单状态',
            prop: 'splittingStatus',
            option: {
              dictInfo: { dict: DictDirection.包裹状态 },
            },
          },
          {
            type: 'select',
            label: '制单人',
            prop: 'maker',
            option: {
              dictInfo: { dict: DictDirection.业务员 },
            },
          },
          {
            type: 'date-picker',
            label: '制单日期',
            prop: 'datePicker',
            option: {
              type: 'date',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            label: '标签号',
            prop: 'tagNumber',
          },
        ],
        queryParams: queryParams.value,
  
      },
      btns: [
        // {
        //   title: '上传清关资料',
        //   type: 'primary',
        //   onClick: handleUploadClearance,
        // },

        {
          title: '导出运单详情',
          type: 'primary',
          onclick: exportDatails,
        },

        {
          title: '导入订单',
          type: 'info',
          onClick: handleImport,
        },

        {
          title: '导出订单列表',
          type: 'warning',
          onClick: handleExport,
        },
        {
          title: '打标签',
          type: 'success',
          disabled: multiple.value,
          onClick: handlePrintLabel,
        },
        {
          title: '打印面单',
          type: 'danger',
          disabled: multiple.value,
          onClick: DownLoadTag,
        },

        {
          title: '签入',
          type: 'info',
          disabled: multiple.value,
          onClick: handleCheckIn,
        },
        {
          title: '强制制单',
          type: 'danger',
          onClick: handleForcePlaceOrder,
          disabled: multiple.value,
        },
        {
          title: '批量修改价格',
          type: 'info',
          disabled: multiple.value,
          onClick() {
            priceDialog.value = true
          },
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },

          { label: '客户单号', align: 'center', prop: 'waybillNo' },
          { label: '主转单号', align: 'center', prop: 'mainTransferOrderNo' },
          { label: '客户名称', align: 'center', prop: 'customerName' },
          { label: '销售产品',
            align: 'center',
            prop: 'marketProducts',
            autoFormatter: {
              dict: DictDirection.产品,
              rowKey: 'marketProducts',
            } },
          { label: '总实重', align: 'center', prop: 'receivingTotalWeight' },
          { label: '材积重', align: 'center', prop: 'receivingTotalWood' },
          { label: '收货体积重', align: 'center', prop: 'volumeWeightTotal' },
          { label: '计费重', align: 'center', prop: 'receivingTotalCharging' },
          { label: '件数', align: 'center', prop: 'receivingTotal' },
          { label: '订单状态',
            align: 'center',
            prop: 'splittingStatus',
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'splittingStatus',
            } },
          { label: '所属站点',
            align: 'center',
            prop: 'areaCode',
            autoFormatter: {
              dict: DictDirection.收货站点,
              rowKey: 'areaCode',
            } },
          { label: '拣货站点',
            align: 'center',
            prop: 'receivingSite',
            autoFormatter: {
              dict: DictDirection.收货站点,
              rowKey: 'receivingSite',
            } },
          { label: '创建日期', align: 'center', prop: 'orderTime' },
          { label: '邮编', align: 'center', prop: 'consigneePostcode' },
          { label: '国家',
            align: 'center',
            prop: 'consigneeCountry',
            autoFormatter: {
              dict: DictDirection.国家,
              rowKey: 'consigneeCountry',
            } },
          { label: '打印标签次数', align: 'center', prop: 'printTagCount' },
          { label: '标签号', align: 'center', prop: 'tagNumber' },
          { label: '货物类型', align: 'center', prop: 'goodsType' },
          { label: '业务员', align: 'center', prop: 'businessManager' },
          { label: '制单人', align: 'center', prop: 'maker' },
          { label: '制单日期', align: 'center', prop: 'makerDate' },
          { label: '报关件', align: 'center', prop: 'customsDeclaration' },
          { label: '备注', align: 'center', prop: 'remarks' },
          { label: '系统订单号', align: 'center', prop: 'orderNo', width: '160px' },
          {
            label: '操作',
            width: '252px',
            fixed: 'right',
            align: 'center',
            render(h, params) {
              const buttons = [    
                {
                  label: '退回制单',
                  clickFun: handleSeniorUpdate,
                },
                {
                  label: '扣件',
                  clickFun: handleFasteners,
                },
                {
                  label: '应收费',
                  clickFun: handleManagementOfSurcharges,
                },
                
                {
                  label: '打单详情',
                  clickFun: handleUps,
                },
                {
                  label: '撤单',
                  clickFun: retuenDel,
                },
                {
                  label: '打单',
                  clickFun: playUps,
                },
                {
                  label: '打标签',
                  clickFun: handlePrintLabel2,
                },

              ]
              return [
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    onClick: () => { handleUpdate(params.row) },
                  },
                  {
                    default: () => '修改',
                  },
                  
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    // icon: el.icon,
                    onClick: () => { handleRouterPush(params.row) },
                  },
                  {
                    default: () => '详情',
                  },
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  SelfDropdown,
                  {
                    items: [
                      ...buttons,
                    ],
                    onHandleCommand(command) {
                      command.clickFun && command.clickFun(params.row)
                    },
                  },
                ),
              ]
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: orderList,
      customKey: 'express/NoMainBusiness/externalChannels/externalOrder',
    }
  },
  set(val) {
    return val
  },
  // customKey: 'express-orderInfo',
})
</script>
<style lang="less" scoped>
/deep/.is-guttered {
  padding: 5px;
}
</style>
